<template>
    <div>
        <el-form ref="pointFormRef" :model="pointForm" size="default" :inline="true" class="point-form common-search-form">
            <!-- <el-form-item prop="projectName">
            <el-input v-model="pointForm.projectName" placeholder="搜索楼盘名称" :suffix-icon="Search"
                      clearable
            />
        </el-form-item> -->
            <el-form-item prop="projectName">
                <houseSearch :project-name="pointForm.projectName" @onSelect="changeProjectName"></houseSearch>
            </el-form-item>
            <el-form-item prop="areas">
                <div class="flex-form-item">
                    <!-- <el-button class="button-item">
                        区域
                    </el-button> -->
                    <el-cascader v-model="pointForm.areas" :options="commonList.regionList" :props="optionProps" filterable
                        clearable placeholder="请选择区域" @change="onChangeArea" />
                </div>
            </el-form-item>
            <el-form-item prop="pointStates">
                <div class="flex-form-item">
                    <!-- <el-button class="button-item">
                        点位状态
                    </el-button> -->
                    <el-select v-model="pointForm.pointStates" placeholder="请选择点位状态" class="select" multiple clearable
                        collapse-tags @change="changePointStates">
                        <template #prefix>
                            <div class="label">
                                点位状态
                            </div>
                        </template>
                        <el-option v-for="(item, index) in commonList.pointStatusList" :key="index" :label="item.name"
                            :value="item.code" />
                    </el-select>
                </div>
            </el-form-item>
            <el-form-item prop="industryTaboos">
                <div class="flex-form-item">
                    <!-- <el-button class="button-item">
                        禁忌行业
                    </el-button> -->
                    <el-select v-model="pointForm.industryTaboos" placeholder="请选择禁忌行业" class="select" multiple clearable
                        collapse-tags @change="changeIndustry">
                        <template #prefix>
                            <div class="label">
                                禁忌行业
                            </div>
                        </template>
                        <el-option v-for="(item, index) in commonList.industryList" :key="index" :label="item.name"
                            :value="item.code" />
                    </el-select>
                </div>
            </el-form-item>
            <el-form-item prop="machineNum" class="machine-num">
                <!-- <el-select v-model="pointForm.machineNum" placeholder="请选择" class="select"> -->
                <!-- <template #prefix>
                    <div class="label">
                        媒体编码
                    </div>
                </template> -->
                <el-input v-model="pointForm.machineNum" :placeholder="+optionData.selectNum === 1 ? '搜索媒体编码' : '搜索点位编码'"
                    clearable class="input-with-select" @change="changeMachineNume">
                    <template #prepend>
                        <el-select v-model="optionData.selectNum" placeholder="媒体编码" style="width: 115px;">
                            <el-option label="媒体编码" value="1" />
                            <el-option label="点位编码" value="2" />
                        </el-select>
                    </template>
                </el-input>
                <!-- </el-select> -->
            </el-form-item>
            <el-form-item>
                <el-button @click="onResetForm(pointFormRef)">
                    重置
                </el-button>
                <el-button @click="onExportPoint(props.activeName)">
                    导出
                </el-button>
                <el-button @click="onBatchImport">
                    批量导入
                </el-button>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="switchBuildingDrawer('addPoint', null)">
                    新建点位
                </el-button>
            </el-form-item>
        </el-form>
        <xc-table id="xc-table" ref="tableDataRef" v-loading="optionData.loading" :data="tableData" :columns="columns"
            :row-config="rowConfig" :page-obj="pageObj" :fit="true" @handleCurrentChange="changePage"
            @handleSizeChange="changePageSize">
            <template #status="{ row }" width="100px">
                <label :class="'reviewStatus' + row.status"></label>

                <el-button type="text" class="status-button">
                    {{ getStatusName(row.status) }}
                </el-button>
                <!-- <el-button v-else-if="+row.status === 5" type="text" class="status-button">
                    维护
                </el-button>
                <el-button v-else-if="+row.status === 6" type="text" class="status-button">
                    下架
                </el-button> -->
                <!-- <span v-else>-</span> -->
            </template>
        </xc-table>
        <pagination :page-no="pageObj.pageNo" :page-size="pageObj.pageSize" :total="pageObj.total" class="pagination"
            @changePage="changePage" @changePageSize="changePageSize"></pagination>

        <batch-import v-model:isPointDrawerShow="optionData.isPointDrawerShow" :active-name="activeName"
            @onAddPoint="onAddPointCallBack" @onCancelCallBack="onCancelCallBack"></batch-import>
        <editPoint :id="optionData.id" v-model:isEditPointDrawerShow="isEditPointDrawerShow"
            :sign-type="optionData.signType" @onEditPointConfirm="onSearchList()"></editPoint>
        <BuildingDrawer v-model:show="buildingDrawerShow" :default-data="buildingDrawerData" :audit-status="[3]"
            @onDataChange="onSearchList()">
        </BuildingDrawer>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref, computed, onMounted, defineProps, watch, nextTick } from 'vue';
import { useStore } from 'vuex';
import {
    queryInnerPointList,
    queryOutPointList,
    queryInnerBoxList,
    queryOutBoxList,
    queryBarrierList,
    queryGatewayList,
    exportInnerPoint,
    exportOutPoint,
    exportInnerBoxMedia,
    exportOutBoxMedia,
    exportBarrierMedia,
    exportGatewayMedia,
} from '@/api/pointManage';
import houseSearch from '@/components/HouseSearch.vue';
import pagination from '@/components/Pagination.vue';
import editPoint from '../../houseManage/components/EditPoint.vue';
import batchImport from './BatchImport.vue';
import BuildingDrawer from '@/views/resource/components/buildingDrawer/Index.vue';
import { downLoadCommon } from '@/utils/common';
import XcTable from '@x-tech/fe-pc-components/src/components/XcTableTemplate/index.vue';
import { setTableMaxHeight } from '@/utils/common';


function getStatusName(s: number) {
    const state = commonList.value.pointStatusList.find((item: any) => {
        return item.code === s;
    })
    return state.name || '-';
}

const props = defineProps({
    name: {
        type: String,
        default: '',
    },
    activeName: {
        type: String,
        default: '',
    },
});

const store = useStore();

const commonList: any = computed(() => store.state.app.common.CommonList);
const isEditPointDrawerShow = ref(false);
const supplierAreaList = store.state.app.common.supplierAreaList;
const buildingDrawerShow = ref(false);
const buildingDrawerData = ref<any>({
    areaArr: [],
    buildingId: '',
    buildingName: '',
    mediaPosition: 1,
});

const mediaPosition = computed(() => {
    // mediaPosition-媒体位置：1.梯内，2.梯外，3.出入门
    let mediaPosition = null;
    if (['innerPoint', 'innerBox'].includes(props.activeName)) {
        mediaPosition = 1;
    }
    if (['outPoint', 'outBox'].includes(props.activeName)) {
        mediaPosition = 2;
    }
    if (['gateway', 'barrier'].includes(props.activeName)) {
        mediaPosition = 3;
    }
    return mediaPosition;
});
const optionProps = {
    value: 'id',
    label: 'name',
    children: 'childList',
};

const optionData = reactive({
    ponitItem: {},
    selectNum: '',
    loading: false,
    isPointDrawerShow: false,
    id: '',
    signType: '',
});
const tableDataRef: any = ref(null);
const tableData = ref([]);
const maxTableHeight = ref(0);
const columns = ref([
    { label: '楼盘名', key: 'premisesName', prop: { minWidth: '200px', fixed: 'left' } },
    { label: '媒体编码', key: 'machineNum', prop: { minWidth: '180px' } },
    { label: '区域', key: 'provenceAndCityAndArea', prop: { minWidth: '240px' } },
    { label: '点位状态', key: 'status', prop: { minWidth: '140px' }, render: true },
    { label: '点位编码', key: 'pointNum', prop: { minWidth: '200px' } },
    { label: '禁忌行业', prop: { minWidth: '120px' }, key: 'tabooIndustryName' },
]);

const pointForm = reactive({
    projectName: '', // 楼盘名称
    areas: [], // 区域
    pointStates: '', // 点位状态
    industryTaboos: '', // 楼盘禁忌行业
    machineNum: '', // 媒体编码/机器码
    pointNum: '', // 点位编码
});

const pageObj = reactive({
    pageSize: 10, // 每页条数
    pageNo: 1, // 当前页
    total: 0,
});
const pointFormRef: any = ref(null);

const onBatchImport = async (): Promise<void> => {
    optionData.isPointDrawerShow = true;
};

const getQueryParam = (): any => {
    if (+optionData.selectNum === 2) {
        pointForm.pointNum = pointForm.machineNum;
    }
    return {
        ...pointForm,
        machineNum: +optionData.selectNum === 1 ? pointForm.machineNum : '',
        pageNo: pageObj.pageNo,
        pageSize: pageObj.pageSize,
    };
};

// 查询方法
const queryInnerPointListFun = async (): Promise<void> => {
    let res: any = {};
    try {
        res = await queryInnerPointList(getQueryParam());
    } catch (error) {
        console.log(error);
    }
    return res;
};

const queryOutPointListFun = async (): Promise<void> => {
    let res: any = {};
    try {
        res = await queryOutPointList(getQueryParam());
    } catch (error) {
        console.log(error);
    }
    return res;
};

const queryInnerBoxListFun = async (): Promise<void> => {
    let res: any = {};
    try {
        res = await queryInnerBoxList(getQueryParam());
    } catch (error) {
        console.log(error);
    }
    return res;
};

const queryOutBoxListFun = async (): Promise<void> => {
    let res: any = {};
    try {
        res = await queryOutBoxList(getQueryParam());
    } catch (error) {
        console.log(error);
    }
    return res;
};

const queryBarrierListFun = async (): Promise<void> => {
    let res: any = {};
    try {
        res = await queryBarrierList(getQueryParam());
    } catch (error) {
        console.log(error);
    }
    return res;
};

const queryGatewayListFun = async (): Promise<void> => {
    let res: any = {};
    try {
        res = await queryGatewayList(getQueryParam());
    } catch (error) {
        console.log(error);
    }
    return res;
};

// 导出接口

const exportInnerPointFun = async (): Promise<void> => {
    let res: any = {};
    try {
        res = await exportInnerPoint();
    } catch (error) {
        console.log(error);
    }
    console.log('exportInnerPoint res', res);
    return res;
};

const exportOutPointFun = async (): Promise<void> => {
    let res: any = {};
    try {
        res = await exportOutPoint();
    } catch (error) {
        console.log(error);
    }
    return res;
};

const exportInnerBoxMediaFun = async (): Promise<void> => {
    let res: any = {};
    try {
        res = await exportInnerBoxMedia();
    } catch (error) {
        console.log(error);
    }
    console.log('exportInnerBoxMedia res', res);
    return res;
};

const exportOutBoxMediaFun = async (): Promise<void> => {
    let res: any = {};
    try {
        res = await exportOutBoxMedia();
    } catch (error) {
        console.log(error);
    }
    console.log('exportOutBoxMedia res', res);
    return res;
};

const exportBarrierMediaFun = async (): Promise<void> => {
    let res: any = {};
    try {
        res = await exportBarrierMedia();
    } catch (error) {
        console.log(error);
    }
    return res;
};

const exportGatewayMediaFun = async (): Promise<void> => {
    let res: any = {};
    try {
        res = await exportGatewayMedia();
    } catch (error) {
        console.log(error);
    }
    return res;
};

const handleCommandQueryMap = {
    innerPoint: queryInnerPointListFun,
    outPoint: queryOutPointListFun,
    innerBox: queryInnerBoxListFun,
    outBox: queryOutBoxListFun,
    barrier: queryBarrierListFun,
    gateway: queryGatewayListFun,
};

const handleCommandExportMap = {
    innerPoint: exportInnerPointFun,
    outPoint: exportOutPointFun,
    innerBox: exportInnerBoxMediaFun,
    outBox: exportOutBoxMediaFun,
    barrier: exportBarrierMediaFun,
    gateway: exportGatewayMediaFun,
};

const onSearchList = async (command = ''): Promise<boolean> => {
    if (props.activeName !== props.name && !command) {
        return false;
    }
    Object.keys(handleCommandQueryMap).map(async (key: any): Promise<boolean> => {
        if (key === props.activeName) {
            optionData.loading = true;
            const res = await handleCommandQueryMap[props.activeName]();
            optionData.loading = false;
            tableData.value = res.data.map((item: any) => {
                return {
                    ...item,
                    tabooIndustryName: item.tabooIndustryName || '-',
                    machineNum: item.machineNum || '-',
                };
            });
            pageObj.total = res.total;
            return true;
        }
        return false;
    });
    return false;
};

const onExportPoint = async (command: string): Promise<void> => {
    Object.keys(handleCommandExportMap).map(async (key: any): Promise<boolean> => {
        if (key === command) {
            optionData.loading = true;
            const res = await handleCommandExportMap[command]();
            optionData.loading = false;
            downLoadCommon(res);
            return true;
        }
        return false;
    });
};

const onEditPoint = async (row: any): Promise<void> => {
    optionData.id = row.id;
    optionData.signType = row.signType;
    isEditPointDrawerShow.value = true;
};

// 开关楼盘图
const switchBuildingDrawer = (type: string, row: any) => {
    buildingDrawerShow.value = !buildingDrawerShow.value;
    if (!buildingDrawerShow.value) {
        return;
    }
    // 新增点位
    if (type === 'addPoint') {
        buildingDrawerData.value = {
            areaArr: supplierAreaList.length ? supplierAreaList[0] : [510000, 510100, 510107],
            buildingId: '',
            buildingName: '',
            mediaPosition: 1,
        };
    }
    // 打开楼盘图
    if (type === 'openBuildingTree') {
        buildingDrawerData.value = {
            areaArr: [row.province, row.city, row.area] || [],
            buildingId: row.premisesId,
            buildingName: row.premisesName,
            mediaPosition: mediaPosition.value || 0,
        };
    }
};

const rowConfig = ref([
    {
        color: '#4D88FF',
        name: '编辑',
        type: 'modify',
        on: (data: any) => {
            // console.log(data);
            onEditPoint(data.row);
        },
    },
    {
        color: '#4D88FF',
        name: '楼盘图',
        type: 'buildingShow',
        on: (data: any) => {
            // console.log(data);
            switchBuildingDrawer('openBuildingTree', data.row);
        },
    },
]);

// 改变当前页
const changePage = (page: number) => {
    pageObj.pageNo = page;
    onSearchList();
};

// 改变当前页列表展示数量
const changePageSize = (pageSize: number) => {
    pageObj.pageNo = 1;
    pageObj.pageSize = pageSize;
    onSearchList();
};

const onCancelCallBack = async (): Promise<void> => {
    optionData.isPointDrawerShow = false;
};

const onAddPointCallBack = () => {
    optionData.isPointDrawerShow = false;
    onSearchList();
};

const changeProjectName = (value: any): void => {
    pointForm.projectName = value.name;
    onSearchList();
};

const onChangeArea = async (value: any): Promise<void> => {
    onSearchList();
};

const changePointStates = async (value: any): Promise<void> => {
    onSearchList();
};

const changeIndustry = async (value: any): Promise<void> => {
    onSearchList();
};

const changeMachineNume = async (value: any): Promise<void> => {
    onSearchList();
};

const onResetForm = async (formEl: any): Promise<void> => {
    if (!formEl) {
        return;
    }
    formEl.resetFields();
    onSearchList();
};

onMounted(async () => {
    await nextTick();
    optionData.selectNum = '1';
    onSearchList();
    maxTableHeight.value = setTableMaxHeight('xc-table');
});
watch(
    () => [props.activeName],
    ([activeNameVal]) => {
        onSearchList();
    }
);
</script>

<style lang="scss" scoped>
@mixin status-color($color) {
    background-color: $color;
    width: 6px;
    height: 6px;
    border-radius: 100px 100px 100px 100px;
    opacity: 1;
    display: inline-block;
    margin-bottom: 1px;
}

:deep(.el-table__body) {
    .xc-table-column {
        // background-color: pink;
        height: 52px !important;

        ._cell {
            padding-top: 0;
            padding-bottom: 0;
        }
    }
}

.flex-form-item {
    display: flex;
    flex-direction: row;

    .button-item {
        height: var(--el-button-size);
        border-right: none;

        &:hover,
        &:active {
            background-color: var(--el-button-bg-color, var(--el-color-white));
            border: var(--el-border-base);
            border-color: var(--el-button-border-color, var(--el-border-color-base));
            color: var(--el-button-text-color, var(--el-text-color-regular));
        }
    }
}

.reviewStatus4 {
    @include status-color(#22ac4e);
}

.reviewStatus5 {
    @include status-color(#ffb414);
}

.reviewStatus6 {
    @include status-color(#e60044);
}
.reviewStatus7 {
    @include status-color(#ed5180);
}

.status-button {
    padding-left: 5px;
    color: var(--el-table-text-color);
}

.input-with-select .el-input-group__prepend {
    background-color: var(--el-fill-color-blank);
}

.point-form {
    // margin-bottom: 10px;

    .is-show-prefix {
        ::v-deep(.el-input__prefix) {
            display: none;
        }
    }

    .machine-num {
        ::v-deep(.el-input__inner) {
            width: 170px !important;
        }
    }
}

// ::v-deep {
//     .el-form .el-form-item .el-input__inner {
//         border-radius: inherit;
//     }
// }
</style>
